package com.example.ccj.b.c.custom.file;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.ccj.R;
import com.example.ccj.b.c.custom.TitleBarOnDisplayControl;
import com.example.ccj.b.c.custom.adapter.AdapterExportFileList;
import com.example.ccj.b.c.dialog.BottomFunctionDialog;
import com.example.ccj.b.c.recycler.BaseRecycler;
import com.example.ccj.u.ActivityUtils;
import com.example.ccj.u.FileUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.UriUtils;
import com.example.ccj.u.media.IPictureSelectResultListener;
import com.example.ccj.u.media.MediaUtils;
import com.example.ccj.u.message.UiMessageUtils;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
 * 文件选择展示控件
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/12/26 10:20
 */
public class FilePickControl  extends LinearLayout {

    //本地数据 ： 可随意添加
    public static final int LOCAL = 0;

    //网络图片 ： 不可添加
    public static final int NETWORK = 1;

    //初始数据为网络数据，后期可添加本地数据，要调用类上传网络完毕后才能添加进来
    public static final int NETWORK_AND_LOCAL_UPLOAD = 2;

    //初始数据为网络数据，后期可添加本地数据，先添加后期再通过调用添加的数据进行上传
    public static final int NETWORK_AND_LOCAL_NO_UPLOAD = 3;

    private int loadMode = LOCAL;           //加载模式  默认为加载本地图片模式

    private boolean isCanModify = true;
    private int maxSum = 10;
    private String titleName = "附件";
    private String tagText = "";
    private FileAdapterListener fileAdapterListener;

    private TitleBarOnDisplayControl titleBarOnDisplayControl;
    private BaseRecycler<FileMode> fileBaseRecycler;
    private List<FileMode> fileList;
    private List<FileMode> newAddFileList;
    private AdapterExportFileList adapterExportFileList;



    public FilePickControl(Context context) {
        super(context);
        init();
    }


    public FilePickControl(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init(){
        fileList = new ArrayList<>();
        newAddFileList = new ArrayList<>();
        inflate(getContext(), R.layout.control_file_pick,this);
        fileBaseRecycler = findViewById(R.id.control_file_pick_rec);
        titleBarOnDisplayControl = findViewById(R.id.control_file_pick_title);

    }


    private void addFile(FileMode fileMode){
        if (fileList.contains(fileMode)) {
            LogUtils.e("已选择的文件",fileMode.path);
            ToastUtils.showShort("已选择的文件！");
            return;
        }

        if (fileAdapterListener != null) {
            if (loadMode == NETWORK_AND_LOCAL_UPLOAD) {
                fileAdapterListener.onAdd(fileMode, new FileNetworkAddListener() {
                    @Override
                    public void onComplete(FileMode fm) {
                        newAddFileList.add(fm);
                        fileBaseRecycler.addDataOnTail(fm);
                    }
                });
            } else {
                newAddFileList.add(fileMode);
                fileBaseRecycler.addDataOnTail(fileMode);
                fileAdapterListener.onAdd(fileMode,null);
            }
        } else {
            newAddFileList.add(fileMode);
            fileBaseRecycler.addDataOnTail(fileMode);
        }
    }

    private void delete(FileMode fileMode){
        if (!fileList.contains(fileMode)) {
            LogUtils.e("未选择的文件",fileMode.path);
            ToastUtils.showShort("未选择的文件！");
            return;
        }

        if (fileAdapterListener != null) {
            //先删除网络再删除本地
            if (loadMode == NETWORK_AND_LOCAL_UPLOAD) {
                fileAdapterListener.onDelete(fileMode, new FileNetworkDeleteListener() {
                    @Override
                    public void onComplete(FileMode fm) {
                        newAddFileList.remove(fm);
                        fileBaseRecycler.removeData(fileMode);
                    }
                });
            } else {
                newAddFileList.remove(fileMode);
                fileBaseRecycler.removeData(fileMode);
                fileAdapterListener.onDelete(fileMode,null);
            }
        } else {
            newAddFileList.remove(fileMode);
            fileBaseRecycler.removeData(fileMode);
        }
    }


    public void builder(){
        adapterExportFileList = new AdapterExportFileList(fileList, isCanModify, new FileAdapterDeleteListener() {
            @Override
            public void onDelete(FileMode fileMode, int position) {
                delete(fileMode);
            }
        });
        fileBaseRecycler.setAdapter(fileList,adapterExportFileList);
        titleBarOnDisplayControl.setTitle(titleName);
        titleBarOnDisplayControl.setTag(tagText);
        if (isCanModify) {
            titleBarOnDisplayControl.setImageOnclick(R.mipmap.file_type_file, new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showBottomFunctionDialog();
                }
            });
        }

        //添加文件选择消息监听器，监听文件选择事件发送的消息 ，这个事件依托于BaseActivity的onActivityResult方法进行消息的发送。
        UiMessageUtils.getInstance().addListener(FileUtils.PICK_FILE_RESULT, new UiMessageUtils.UiMessageCallback() {
            @Override
            public void handleMessage(@NonNull UiMessageUtils.UiMessage uiMessage) {
                Intent intent = (Intent) uiMessage.getObject();
                if (intent != null) {
                    Uri uri = intent.getData();
                    if (uri != null) {
                        File file = UriUtils.uri2File(uri);
                        FileMode fileMode = new FileMode();
                        fileMode.file = file;
                        fileMode.path = file.getPath();
                        addFile(fileMode);
                    }
                }
            }
        });
    }


    BottomFunctionDialog dialog;
    List<LocalMedia> localMediaList;
    /**
     * 附件选择模式
     */
    private void showBottomFunctionDialog() {

        if (fileList.size() >= maxSum) {
            ToastUtils.showShort("最多选择" + maxSum);
            return ;
        }

        if (dialog == null) {
            localMediaList = new ArrayList<>();
            dialog = new BottomFunctionDialog(getContext());

            dialog.setFunction("拍摄照片", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MediaUtils mediaUtils = new MediaUtils();
                    mediaUtils.camera(getContext(), new IPictureSelectResultListener() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            if (result != null && !result.isEmpty()) {
                                localMediaList.addAll(result);
                                for (LocalMedia localMedia : result) {
                                    File file = new File(localMedia.getRealPath());
                                    FileMode fileMode = new FileMode();
                                    fileMode.path = file.getPath();
                                    fileMode.file = file;
                                    addFile(fileMode);
                                }
                            }
                        }
                    });
                    dialog.dismiss();
                }
            });


            dialog.setFunction("选择图库图片", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MediaUtils mediaUtils = new MediaUtils();
                    mediaUtils.pickMultiplePicture(getContext(), localMediaList, maxSum, new IPictureSelectResultListener() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            if (result != null && !result.isEmpty()) {
                                localMediaList.addAll(result);
                                for (LocalMedia localMedia : result) {
                                    File file = new File(localMedia.getRealPath());
                                    FileMode fileMode = new FileMode();
                                    fileMode.path = file.getPath();
                                    fileMode.file = file;
                                    addFile(fileMode);
                                }
                            }
                        }
                    });
                    dialog.dismiss();
                }
            });

            dialog.setFunction("选择一个视频", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MediaUtils mediaUtils = new MediaUtils();
                    mediaUtils.pickAMedia(getContext(), localMediaList, new IPictureSelectResultListener() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            if (result != null && !result.isEmpty()) {
                                localMediaList.addAll(result);
                                for (LocalMedia localMedia : result) {
                                    File file = new File(localMedia.getRealPath());
                                    FileMode fileMode = new FileMode();
                                    fileMode.path = file.getPath();
                                    fileMode.file = file;
                                    addFile(fileMode);
                                }
                            }
                        }
                    });
                    dialog.dismiss();
                }
            });

            dialog.setFunction("选择一个音频", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MediaUtils mediaUtils = new MediaUtils();
                    mediaUtils.pickAAudio(getContext(), localMediaList, new IPictureSelectResultListener() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            if (result != null && !result.isEmpty()) {
                                localMediaList.addAll(result);
                                for (LocalMedia localMedia : result) {
                                    File file = new File(localMedia.getRealPath());
                                    FileMode fileMode = new FileMode();
                                    fileMode.path = file.getPath();
                                    fileMode.file = file;
                                    addFile(fileMode);
                                }
                            }
                        }
                    });
                    dialog.dismiss();
                }
            });

            dialog.setFunction("本地文件", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("*/*");//   /*/ 此处是任意类型任意后缀
                    //intent.setType(“audio/*”) //选择音频
                    //intent.setType(“video/*”) //选择视频 （mp4 3gp 是android支持的视频格式）
                    //intent.setType(“video/*;image/*”)//同时选择视频和图片
                    intent.addCategory(Intent.CATEGORY_OPENABLE);

                    //跳转至本地文件选择界面，依托BaseActivity的onActivityResult方法进行文件选择后的消息发送。
                    ActivityUtils.getTopActivity().startActivityForResult(intent,FileUtils.PICK_FILE_RESULT);
                    dialog.dismiss();
                }
            });

            dialog.show();
        } else {
            dialog.show();
        }
    }


    /**
     * 设置加载模式
     *  LOCAL : 本地图片
     *  NETWORK ： 网络图片
     *  NETWORK_AND_LOCAL_UPLOAD ： 网络和可以添加本地 先上传后更新
     *  NETWORK_AND_LOCAL_NO_UPLOAD ：  网络和可以添加本地 先更新后上传
     */
    public FilePickControl setLoadMode(int loadMode) {
        this.loadMode = loadMode;
        if (loadMode == NETWORK) isCanModify = false;
        return this;
    }

    //设置是否可修改
    public FilePickControl setCanModify(boolean canModify) {
        isCanModify = canModify;
        return this;
    }

    /**
     * 设置最大选择数量
     * @param maxSum 最大选择数量
     * @return 1
     */
    public FilePickControl setMaxSum(int maxSum) {
        this.maxSum = maxSum;
        return this;
    }

    /**
     * 设置标题名称
     * @param titleName 标题名称
     * @return 1
     */
    public FilePickControl setTitleName(String titleName) {
        this.titleName = titleName;
        return this;
    }

    /**
     * 设置原始文件
     * @param fileList 原始文件
     * @return 1
     */
    public FilePickControl setFileModeList(@NonNull List<FileMode> fileList) {
        this.fileList = fileList;
        return this;
    }

    /**
     * 设置原始文件
     * @param fileList 原始文件
     * @return 1
     */
    public FilePickControl setFileList(List<File> fileList) {
        if (fileList != null) {
            for (File file : fileList) {
                FileMode fileMode = new FileMode();
                fileMode.file = file;
                fileMode.path = file.getPath();
                this.fileList.add(fileMode);
            }

        }
        return this;
    }

    /**
     * 设置提示文字
     * @param tagText 提示文字
     * @return 1
     */
    public FilePickControl setTagText(String tagText) {
        this.tagText = tagText;
        return this;
    }

    /**
     * 设置文件增删回调
     * @return 1
     */
    public FilePickControl setFileAdapterListener(FileAdapterListener fileAdapterListener) {
        this.fileAdapterListener = fileAdapterListener;
        return this;
    }




    public int getLoadMode() {
        return loadMode;
    }
    public boolean isCanModify() {
        return isCanModify;
    }
    public int getMaxSum() {
        return maxSum;
    }
    public String getTitleName() {
        return titleName;
    }
    public String getTagText() {
        return tagText;
    }
    public List<FileMode> getFileList() {
        return fileList;
    }
    public FileAdapterListener getFileAdapterListener() {
        return fileAdapterListener;
    }

    /**
     * 获取头view
     * 修改头部的文本大小等
     * @return 头view
     */
    public TitleBarOnDisplayControl getTitleBarOnDisplayControl() {
        return titleBarOnDisplayControl;
    }
    public BaseRecycler<FileMode> getFileBaseRecycler() {
        return fileBaseRecycler;
    }



    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        //销毁时取消消息监听
        UiMessageUtils.getInstance().removeListeners(FileUtils.PICK_FILE_RESULT);
    }

}
